<?php

namespace App\Jobs\SystemNotify;

use App\Models\System\SystemNotifyCenterModel;
use App\Service\System\SystemNotifyService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;

class DelayPushJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 延时推送记录id
     *
     * @var int
     */
    public int $systemNotifyId;
    /**
     * 延时推送时间
     *
     * @var int
     */
    public int $delayNotifyTime;

    /**
     * @param int $id
     * @param int $delayNotifyTime
     */
    public function __construct(int $id, int $delayNotifyTime)
    {
        $this->systemNotifyId  = $id;
        $this->delayNotifyTime = $delayNotifyTime;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            logInfo(
                "系统消息延时推送 【 {$this->systemNotifyId} 】",
                collect([
                    "id"              => $this->systemNotifyId,
                    "delayNotifyTime" => Carbon::createFromTimestamp($this->delayNotifyTime)
                                               ->format("Y-m-d H:i:s")
                ]),
                true,
                false
            );


            $systemNotifyCenterModel = SystemNotifyCenterModel::query()->where("id", $this->systemNotifyId)->first();
            if (
                empty($systemNotifyCenterModel)
                ||
                $systemNotifyCenterModel->status != SystemNotifyCenterModel::NOTIFY_STATUS_1
                ||
                $systemNotifyCenterModel->isDeleted
            ) {
                throw new \Exception("延时消息不存在或状态异常,请核查后重试");
            }

            if ($systemNotifyCenterModel->notifyType != SystemNotifyCenterModel::NOTIFY_TYPE_DELAY) {
                throw new \Exception("推送类型不合法！仅支持延时消息推送类型");
            }

            if ($systemNotifyCenterModel->delayNotifyTime != $this->delayNotifyTime) {
                throw new \Exception("延时推送时间发生变更，取消当次执行任务");
            }

            SystemNotifyService::send($this->systemNotifyId);
        } catch (\Exception $exception) {
            logException("系统消息延时推送失败: {$exception->getMessage()}", $exception, ["id" => $this->systemNotifyId], true, true);
        }
    }
}
